import storage from "store";
import { login } from "../../api/user/login";
import { ACCESS_TOKEN } from "../mutation-types";
import { welcome } from "../../utils/util";

const user = {
  state: {
    token: "",
    name: "",
    welcome: "",
    avatar: "",
    roles: [],
    info: {}
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name;
      state.welcome = welcome;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_INFO: (state, info) => {
      state.info = info;
    }
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            console.log(response);
            const result = response.data.data;
            // const token = response.headers.authorization;
            const token = result.token;
            // TODO login 登录:token的作用, 只是用于判断用户是否登录, 无其它作用
            storage.set(ACCESS_TOKEN, token, 24 * 60 * 60 * 1000);
            storage.set("userInfo", result.admin_info);
            storage.set("userId", result.admin_info.id);
            storage.set("userName", result.admin_info.name);
            commit("SET_TOKEN", token);
            commit("SET_NAME", {
              name: result.admin_info.name,
              welcome: welcome()
            });
            resolve(response);
            console.log("登录完成");
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 登出
    Logout({ commit, state }) {
      console.log(state);
      // return new Promise((resolve) => {
      //   logout(state.token).then(() => {
      //     resolve()
      //   }).catch(() => {
      //     resolve()
      //   }).finally(() => {
      //     commit('SET_TOKEN', '')
      //     commit('SET_ROLES', [])
      //     storage.remove(ACCESS_TOKEN)
      //   })
      // })
      commit("SET_TOKEN", "");
      commit("SET_NAME", "");
      commit("SET_ROLES", []);
      storage.remove(ACCESS_TOKEN);
      storage.remove("userInfo");
      storage.remove("userId");
      storage.remove("userName");
    }
  }
};

export default user;
